import { View } from '@tarojs/components';

import './index.scss';

import type { FC } from 'react';
import classnames from 'classnames';

const PREFIX_CLS = 'my-select-button';

type Value = string | number;

interface SelectButtonProps {
  options: {
    label: string;
    value: Value;
  }[];
  onChange: (value: Value) => void;
  value?: Value;
  disabled?: boolean;
}

const SelectButton: FC<SelectButtonProps> = ({
  options,
  onChange,
  value = options?.[0]?.value,
  disabled = false,
}) => {
  return (
    <View className={PREFIX_CLS}>
      {options.map((item, index) => {
        const isLast = index === options.length - 1;
        const isFirst = index === 0;
        const isPrevActive = options[index + 1]?.value === value;
        const isNextActive = options[index - 1]?.value === value;
        return (
          <View
            className={classnames('item', {
              'item-active': item.value === value,
              'item-first': isFirst,
              'item-last': isLast,
              'item-middle': !isFirst && !isLast,
              'item-prev-active': isPrevActive,
              'item-next-active': isNextActive,
            })}
            key={item.value}
            onClick={(e) => {
              e.stopPropagation();
              if (disabled) return;
              onChange(item.value);
            }}
          >
            {item.label}
          </View>
        );
      })}
    </View>
  );
};

export default SelectButton;
